﻿using System;
using System.Data;
using BP.DA;
using BP.Sys;
using BP.En;
using BP.WF;
using BP.WF.HttpHandler;
using BP.Web;
using BP.Difference;
using BP.Template.Printer;
using DocumentFormat.OpenXml.Office2013.Drawing.ChartStyle;
using System.IO;

namespace BP.CCBill
{
    /// <summary>
    /// 页面功能实体
    /// </summary>
    public class WF_CCBill_Opt : DirectoryPageBase
    {
        #region 构造方法.
        /// <summary>
        /// 构造函数
        /// </summary>
        public WF_CCBill_Opt()
        {
        }
        #endregion 构造方法.

        #region 关联单据.
        /// <summary>
        /// 设置父子关系.
        /// </summary>
        /// <returns></returns>
        public string RefBill_Done()
        {
            try
            {
                string frmID = this.GetRequestVal("FrmID");
                Int64 workID = this.GetRequestValInt64("WorkID");
                GERpt rpt = new GERpt(frmID, workID);

                string pFrmID = this.GetRequestVal("PFrmID");
                Int64 pWorkID = this.GetRequestValInt64("PWorkID");

                //把数据copy到当前的子表单里.
                GERpt rptP = new GERpt(pFrmID, pWorkID);
                rpt.Copy(rptP);
                rpt.PWorkID = pWorkID;
                rpt.SetValByKey("PFrmID", pFrmID);
                rpt.Update();

                //更新控制表,设置父子关系.
                GenerBill gbill = new GenerBill(workID);
                gbill.PFrmID = pFrmID;
                gbill.PWorkID = pWorkID;
                gbill.Update();
                return "执行成功";
            }
            catch (Exception ex)
            {
                return "err@" + ex.Message;
            }
        }
        /// <summary>
        /// 单据初始化
        /// </summary>
        /// <returns></returns>
        public string RefBill_Init()
        {
            DataSet ds = new DataSet();

            #region 查询显示的列
            MapAttrs mattrs = new MapAttrs();
            mattrs.Retrieve(MapAttrAttr.FK_MapData, this.FrmID, MapAttrAttr.Idx);

            DataRow row = null;
            System.Data.DataTable dt = new System.Data.DataTable("Attrs");
            dt.Columns.Add("KeyOfEn", typeof(string));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Width", typeof(int));
            dt.Columns.Add("UIContralType", typeof(int));
            dt.Columns.Add("LGType", typeof(int));

            //设置标题、单据号位于开始位置


            foreach (MapAttr attr in mattrs)
            {
                string searchVisable = attr.atPara.GetValStrByKey("SearchVisable");
                if (searchVisable == "0")
                    continue;
                if (attr.UIVisible == false)
                    continue;
                row = dt.NewRow();
                row["KeyOfEn"] = attr.KeyOfEn;
                row["Name"] = attr.Name;
                row["Width"] = attr.UIWidthInt;
                row["UIContralType"] = attr.UIContralType;
                row["LGType"] = attr.LGType;
                dt.Rows.Add(row);
            }
            ds.Tables.Add(dt);
            #endregion 查询显示的列

            #region 查询语句

            MapData md = new MapData(this.FrmID);

            GEEntitys rpts = new GEEntitys(this.FrmID);

            Attrs attrs = rpts.GetNewEntity.EnMap.Attrs;

            QueryObject qo = new QueryObject(rpts);

            #region 关键字字段.
            string keyWord = this.GetRequestVal("SearchKey");

            if (DataType.IsNullOrEmpty(keyWord) == false && keyWord.Length >= 1)
            {
                qo.addLeftBracket();
                if (BP.Difference.SystemConfig.AppCenterDBVarStr == "@" || BP.Difference.SystemConfig.AppCenterDBVarStr == "?")
                    qo.AddWhere("Title", " LIKE ", BP.Difference.SystemConfig.AppCenterDBType == DBType.MySQL ? (" CONCAT('%'," + BP.Difference.SystemConfig.AppCenterDBVarStr + "SKey,'%')") : (" '%'+" + BP.Difference.SystemConfig.AppCenterDBVarStr + "SKey+'%'"));
                else
                    qo.AddWhere("Title", " LIKE ", " '%'||" + BP.Difference.SystemConfig.AppCenterDBVarStr + "SKey||'%'");
                qo.addOr();
                if (BP.Difference.SystemConfig.AppCenterDBVarStr == "@" || BP.Difference.SystemConfig.AppCenterDBVarStr == "?")
                    qo.AddWhere("BillNo", " LIKE ", BP.Difference.SystemConfig.AppCenterDBType == DBType.MySQL ? ("CONCAT('%'," + BP.Difference.SystemConfig.AppCenterDBVarStr + "SKey,'%')") : ("'%'+" + BP.Difference.SystemConfig.AppCenterDBVarStr + "SKey+'%'"));
                else
                    qo.AddWhere("BillNo", " LIKE ", "'%'||" + BP.Difference.SystemConfig.AppCenterDBVarStr + "SKey||'%'");

                qo.MyParas.Add("SKey", keyWord);
                qo.addRightBracket();

            }
            else
            {
                qo.AddHD();
            }
            #endregion 关键字段查询

            #region 时间段的查询
            string dtFrom = this.GetRequestVal("DTFrom");
            string dtTo = this.GetRequestVal("DTTo");
            if (DataType.IsNullOrEmpty(dtFrom) == false)
            {

                //取前一天的24：00
                if (dtFrom.Trim().Length == 10) //2017-09-30
                    dtFrom += " 00:00:00";
                if (dtFrom.Trim().Length == 16) //2017-09-30 00:00
                    dtFrom += ":00";

                dtFrom = DateTime.Parse(dtFrom).AddDays(-1).ToString("yyyy-MM-dd") + " 24:00";

                if (dtTo.Trim().Length < 11 || dtTo.Trim().IndexOf(' ') == -1)
                    dtTo += " 24:00";

                qo.addAnd();
                qo.addLeftBracket();
                qo.SQL = " RDT>= '" + dtFrom + "'";
                qo.addAnd();
                qo.SQL = "RDT <= '" + dtTo + "'";
                qo.addRightBracket();
            }
            #endregion 时间段的查询

            qo.DoQuery("OID", this.PageSize, this.PageIdx);

            #endregion

            System.Data.DataTable mydt = rpts.ToDataTableField();
            mydt.TableName = "DT";

            ds.Tables.Add(mydt); //把数据加入里面.

            return BP.Tools.Json.ToJson(ds);
        }
        #endregion 关联单据.

        /// <summary>
        /// 获得打印列表
        /// </summary>
        /// <returns></returns>
        public string Printer_Init()
        {
            //1. 获得打印记录.
            FrmPrintDBs dbs = new FrmPrintDBs();
            dbs.Retrieve("FrmID", this.FrmID, "WorkID", this.WorkID);

            //2. 获得打印模版.
            FrmPrintTemplates templates = new FrmPrintTemplates();
            try
            {
                templates.Retrieve("FrmID", this.FrmID, "IsEnable", 1);
            }
            catch (Exception e)
            {
                templates.GetNewEntity.CheckPhysicsTable();
                templates.Retrieve("FrmID", this.FrmID, "IsEnable", 1);
            }

            FrmPrintDB db = null;
            //3. 组织数据.
            foreach (FrmPrintTemplate template in templates)
            {
                Entity en = dbs.GetEntityByKey("FrmPrintTemplateID", template.MyPK);
                if (en == null)
                {
                    db = new FrmPrintDB();
                    db.SetValByKey("FrmPrintTemplateID", template.MyPK);
                    db.SetValByKey("FrmPrintTemplateName", template.Name);
                    db.SetValByKey("RTFFileName", template.GetParaString("FileName"));
                    db.SetValByKey("FrmID", template.FrmID);
                    db.SetValByKey("WorkID", this.WorkID);
                    // 
                    db.SetValByKey("RecNo", "无");
                    db.SetValByKey("RecName", "无");
                    db.SetValByKey("RDT", "无");
                    db.SetValByKey("State", "未打印");
                    if (template.TemplateFileModel == WF.Template.Frm.TemplateFileModel.VSTOForExcel)
                        db.SetValByKey("FileExt", "xlsx");
                    if (template.TemplateFileModel == WF.Template.Frm.TemplateFileModel.VSTOForWord)
                        db.SetValByKey("FileExt", "docx");
                    if (template.TemplateFileModel == WF.Template.Frm.TemplateFileModel.RTF)
                        db.SetValByKey("FileExt", "docx");
                    dbs.AddEntity(db);
                    continue;
                }
                en.SetValByKey("FrmPrintTemplateName", template.Name);
            }

            return BP.Tools.Json.ToJson(dbs.ToDataTableField());
        }
        public string Printer_SelectOne()
        {
            string templateID = this.GetRequestVal("TemplateID");
            string dbMyPK = this.GetRequestVal("DBMyPK");
            string OpenType = this.GetRequestVal("OpenType");
            bool IsRePrint = this.GetRequestValBoolen("IsRePrint");
            FrmPrintTemplate template = new FrmPrintTemplate(templateID);

            FrmPrintDB db = new FrmPrintDB();

            if (DataType.IsNullOrEmpty(dbMyPK) == false && IsRePrint == false)
            {
                db.setMyPK(dbMyPK);
                db.Retrieve();

                string fileName = DBAccess.GenerGUID() + "." + db.GetValByKey("FileExt");

                //1. 生成文件下载.
                string file = SystemConfig.PathOfTemp + "//" + fileName;
                DBAccess.GetFileFromDB(file, "Sys_FrmPrintDB", "MyPK", db.MyPK, "DBFile");

                //2. 记录下载日志.
                BP.CCBill.Dev2Interface.WriteTrack(this.FrmID, this.WorkID.ToString(), "Printer", "打印:" + template.Name);
                string path = "/DataUser/Temp/" + fileName;
                return Printer_UrlReturn(template.TemplateFileModel, dbMyPK, path, OpenType);
            }
            db.FrmID = this.FrmID;
            db.SetValByKey("WorkID", this.WorkID);
            db.SetValByKey("RecNo", WebUser.No);
            db.SetValByKey("RecName", WebUser.Name);
            db.SetValByKey("RDT", DataType.CurrentDateTime);
            db.SetValByKey("FrmPrintTemplateID", template.MyPK);
            db.SetValByKey("FrmPrintTemplateName", template.Name);
            db.SetValByKey("RTFFileName", template.GetParaString("FileName"));
            db.MyPK = DBAccess.GenerGUID();

            if (template.TemplateFileModel == WF.Template.Frm.TemplateFileModel.RTF)
            {
                MapData mapdata = new MapData(this.FrmID);
                WF_WorkOpt wkOpt = new WF_WorkOpt();
                string billUrl = "";
                if (mapdata.EntityType == EntityType.FrmEntityNoName)
                    billUrl = wkOpt.PrintDoc_EntityNoNameDoneIt(this.WorkIDStr, this.FrmID, template);
                else
                {
                    Node nd = null;
                    if (this.NodeID != 0)
                        nd = new Node(this.NodeID);
                    billUrl = wkOpt.PrintDoc_FormDoneIt(null, this.WorkID, this.FID, this.FrmID, template);
                }
                billUrl = billUrl.Replace("file@rtf@", "");
                if (billUrl.EndsWith(".doc"))
                    db.SetValByKey("FileExt", "doc");
                if (billUrl.EndsWith(".pdf"))
                    db.SetValByKey("FileExt", "pdf");

                db.SetValByKey("State", "已打印");
                if (DataType.IsNullOrEmpty(dbMyPK) == false)
                    db.setMyPK(dbMyPK);
                db.Save();
                DBAccess.SaveFileToDB(SystemConfig.PathOfDataUser + billUrl.Replace("/DataUser", ""), "Sys_FrmPrintDB", "MyPK", db.MyPK, "DBFile");
                return Printer_UrlReturn(template.TemplateFileModel, db.MyPK, billUrl, OpenType);
            }

            //
            if (template.TemplateFileModel == WF.Template.Frm.TemplateFileModel.VSTOForExcel)
            {
                string fileTemplagePath = DBAccess.GenerGUID() + ".xlsx";
                string fileFullName = SystemConfig.PathOfTemp + "//" + fileTemplagePath;

                try
                {
                    DBAccess.GetFileFromDB(fileFullName, "Sys_FrmPrintTemplate", "MyPK", templateID, "DBFile");
                }
                catch (Exception ex)
                {
                    throw new Exception("err@获取模板错误：应该是设计人员没有设计打印模板."+ex.Message);
                }

                //@zsy. 根据模版数据生成文件.
                // 生成打印文件.
                BP.Sys.Printer.OfficerHelper help = new BP.Sys.Printer.OfficerHelper();

                try
                {
                    help.MakeExcelFile(this.FrmID, fileFullName, template, this.WorkID);
                }
                catch (Exception ex)
                {
                    throw new Exception("err@生成Excel打印文件错误:" + ex.Message);
                }

                //保存文件到数据库.
                db.SetValByKey("FileExt", "xlsx");
                if (DataType.IsNullOrEmpty(dbMyPK) == false)
                    db.setMyPK(dbMyPK);
                db.Save();
                DBAccess.SaveFileToDB(fileFullName, "Sys_FrmPrintDB", "MyPK", db.MyPK, "DBFile");
                string path = "/DataUser/Temp/" + fileTemplagePath;
                return Printer_UrlReturn(template.TemplateFileModel, db.MyPK, path, OpenType);
            }

            if (template.TemplateFileModel == WF.Template.Frm.TemplateFileModel.VSTOForWord)
            {
                string fileTemplagePath = DBAccess.GenerGUID() + ".docx";
                //string fileTemplagePath = Guid.NewGuid().ToString() + ".docx";
                string fileFullName = SystemConfig.PathOfTemp + "//" + fileTemplagePath;
                fileFullName= fileFullName.Replace("/", "\\");
                fileFullName = fileFullName.Replace("\\\\", "\\");

                try
                {
                    DBAccess.GetFileFromDB(fileFullName, "Sys_FrmPrintTemplate", "MyPK", templateID, "DBFile");
                }
                catch (Exception ex)
                {
                    throw new Exception("err@获取Word模板错误：应该是设计人员没有设计打印模板.");
                }

                BP.Sys.Printer.OfficerHelper help = new BP.Sys.Printer.OfficerHelper();
                help.MakeDocFile(this.FrmID, fileFullName, template, this.WorkID);

                
                //FileInfo fi = new FileInfo(fileFullName);
                if (File.Exists(fileFullName))
                {
                    //保存文件到数据库.
                    db.SetValByKey("FileExt", "docx");
                    if (DataType.IsNullOrEmpty(dbMyPK) == false)
                        db.setMyPK(dbMyPK);
                    db.Save();
                    DBAccess.SaveFileToDB(fileFullName, "Sys_FrmPrintDB", "MyPK", db.MyPK, "DBFile");
                    string path = "/DataUser/Temp/" + fileTemplagePath;
                    return Printer_UrlReturn(template.TemplateFileModel, db.MyPK, path, OpenType);
                }
                else {
                    throw new Exception("Word模板操作错误,请稍后重新操作.");
                }  
            }

            if (template.TemplateFileModel == WF.Template.Frm.TemplateFileModel.WPS)
            {
                //@zsy. 
            }
            throw new Exception("err@没有判断的类型:" + template.TemplateFileModel);
        }
        public string Printer_UrlReturn(WF.Template.Frm.TemplateFileModel tmodel, string MyPK, string path, string OpenType)
        {
            if (tmodel == WF.Template.Frm.TemplateFileModel.VSTOForExcel && OpenType.Equals("1"))
            {
                string url = "excelform://-fromccflow,AppID=FrmPrinter,MyPK=" + MyPK + ",Token=" + WebUser.Token + ",FrmID=" + this.FrmID;
                return url;
            }

            if (tmodel == WF.Template.Frm.TemplateFileModel.VSTOForWord && OpenType.Equals("1"))
            {
                string url = "wordform://-fromccflow,AppID=FrmPrinter,MyPK=" + MyPK + ",Token=" + WebUser.Token + ",FrmID=" + this.FrmID + ",WorkID=" + this.WorkID;
                return url;
            }
            return path;
        }
    }
}
